<template>
  <div class="scan-policies-container">
    <el-card class="policies-card">
      <template #header>
        <div class="card-header">
          <h2>扫描策略管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="showCreatePolicyDialog = true">
              <el-icon><Plus /></el-icon>
              新建策略
            </el-button>
            <el-button @click="cloneSelectedPolicy">
              <el-icon><CopyDocument /></el-icon>
              克隆策略
            </el-button>
            <el-button @click="importPolicy">
              <el-icon><Upload /></el-icon>
              导入策略
            </el-button>
            <el-button @click="exportSelectedPolicies">
              <el-icon><Download /></el-icon>
              导出选中
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-filter-container">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="searchQuery"
              placeholder="搜索策略名称或描述"
              prefix-icon="Search"
              clearable
              @input="handleSearch"
            />
          </el-col>
          <el-col :span="8">
            <el-select
              v-model="filterPolicyType"
              placeholder="选择策略类型"
              clearable
              @change="handleFilter"
            >
              <el-option
                v-for="type in policyTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-select
              v-model="filterStatus"
              placeholder="选择状态"
              clearable
              @change="handleFilter"
            >
              <el-option label="已启用" value="enabled" />
              <el-option label="已禁用" value="disabled" />
            </el-select>
          </el-col>
        </el-row>
      </div>

      <!-- 策略列表 -->
      <div class="policies-table-container">
        <el-table
          v-loading="loading"
          :data="paginatedPolicies"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          @row-dblclick="editPolicy"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="策略名称" min-width="180">
            <template #default="scope">
              <div class="policy-name-cell">
                <div class="policy-name">{{ scope.row.name }}</div>
                <div class="policy-type">
                  <el-tag size="small" :type="getPolicyTypeTag(scope.row.type)">
                    {{ getPolicyTypeLabel(scope.row.type) }}
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="扫描类型" min-width="150">
            <template #default="scope">
              <div class="scan-types">
                <el-tag 
                  v-for="scanType in scope.row.scanTypes" 
                  :key="scanType"
                  size="small"
                  class="mr-2"
                >
                  {{ getScanTypeLabel(scanType) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="扫描速度" width="100">
            <template #default="scope">
              <el-rate 
                v-model="scope.row.scanSpeed" 
                disabled 
                :max="3"
                show-score
              />
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200">
            <template #default="scope">
              <div class="policy-description" :title="scope.row.description">
                {{ scope.row.description }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="创建时间" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="enabled"
                inactive-value="disabled"
                active-text="启用"
                inactive-text="禁用"
                @change="updatePolicyStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="editPolicy(scope.row)"
                size="small"
                title="编辑策略"
              >
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button
                type="primary"
                @click="runPolicyScan(scope.row)"
                size="small"
                title="立即扫描"
              >
                <el-icon><Play /></el-icon>
              </el-button>
              <el-button
                type="danger"
                link
                @click="deletePolicy(scope.row)"
                size="small"
                title="删除策略"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredPolicies.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑策略对话框 -->
    <el-dialog
      v-model="showCreatePolicyDialog"
      :title="editingPolicy ? '编辑扫描策略' : '新建扫描策略'"
      width="800px"
      @close="resetPolicyForm"
    >
      <el-form
        ref="policyFormRef"
        :model="policyForm"
        :rules="policyFormRules"
        label-width="120px"
      >
        <el-form-item label="策略名称" prop="name">
          <el-input
            v-model="policyForm.name"
            placeholder="请输入策略名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="策略类型" prop="type">
          <el-select
            v-model="policyForm.type"
            placeholder="请选择策略类型"
          >
            <el-option
              v-for="type in policyTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="policyForm.description"
            type="textarea"
            placeholder="请输入策略描述"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 扫描配置 -->
        <el-divider>扫描配置</el-divider>
        
        <el-form-item label="扫描类型" prop="scanTypes">
          <el-checkbox-group v-model="policyForm.scanTypes">
            <el-checkbox 
              v-for="type in availableScanTypes" 
              :key="type.value"
              :label="type.value"
              border
              class="mr-4 mb-2"
              :disabled="policyForm.scanTypes.length === 1 && isSelectedScanType(type.value)"
            >
              {{ type.label }}
            </el-checkbox>
          </el-checkbox-group>
          <div class="form-hint">至少选择一种扫描类型</div>
        </el-form-item>

        <el-form-item label="扫描速度" prop="scanSpeed">
          <el-rate 
            v-model="policyForm.scanSpeed" 
            :max="3"
            :texts="['低速', '中速', '高速']"
            show-score
          />
          <div class="form-hint">低速更准确但耗时更长，高速效率更高但可能有遗漏</div>
        </el-form-item>

        <el-form-item label="并发数" prop="concurrency">
          <el-slider
            v-model="policyForm.concurrency"
            :min="1"
            :max="20"
            :marks="{
              1: '1',
              5: '5',
              10: '10',
              15: '15',
              20: '20'
            }"
          />
        </el-form-item>

        <el-form-item label="超时设置（秒）" prop="timeout">
          <el-input-number
            v-model="policyForm.timeout"
            :min="10"
            :max="3600"
            :step="10"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="重试次数" prop="retryCount">
          <el-input-number
            v-model="policyForm.retryCount"
            :min="0"
            :max="10"
            style="width: 100%"
          />
        </el-form-item>

        <!-- 漏洞配置 -->
        <el-divider>漏洞配置</el-divider>
        
        <el-form-item label="包含漏洞类型" prop="includedVulnerabilities">
          <el-select
            v-model="policyForm.includedVulnerabilities"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入漏洞类型"
            style="width: 100%"
          >
            <el-option
              v-for="vuln in commonVulnerabilityTypes"
              :key="vuln.value"
              :label="vuln.label"
              :value="vuln.value"
            />
          </el-select>
          <div class="form-hint">留空表示包含所有漏洞类型</div>
        </el-form-item>

        <el-form-item label="排除漏洞类型" prop="excludedVulnerabilities">
          <el-select
            v-model="policyForm.excludedVulnerabilities"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入漏洞类型"
            style="width: 100%"
          >
            <el-option
              v-for="vuln in commonVulnerabilityTypes"
              :key="vuln.value"
              :label="vuln.label"
              :value="vuln.value"
            />
          </el-select>
          <div class="form-hint">排除的漏洞类型优先级高于包含的类型</div>
        </el-form-item>

        <el-form-item label="严重程度阈值" prop="severityThreshold">
          <el-select
            v-model="policyForm.severityThreshold"
            placeholder="请选择严重程度阈值"
          >
            <el-option label="所有级别" value="all" />
            <el-option label="仅高危" value="high" />
            <el-option label="高危和中危" value="medium" />
            <el-option label="高危、中危和低危" value="low" />
          </el-select>
        </el-form-item>

        <el-form-item label="启用指纹识别" prop="enableFingerprinting">
          <el-switch v-model="policyForm.enableFingerprinting" />
        </el-form-item>

        <el-form-item label="启用被动扫描" prop="enablePassiveScan">
          <el-switch v-model="policyForm.enablePassiveScan" />
        </el-form-item>

        <el-form-item label="启用深度检测" prop="enableDeepScan">
          <el-switch v-model="policyForm.enableDeepScan" />
        </el-form-item>

        <!-- 高级配置 -->
        <el-divider>高级配置</el-divider>
        
        <el-form-item label="HTTP请求头">
          <el-table :data="policyForm.httpHeaders" border style="width: 100%">
            <el-table-column prop="name" label="名称" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.name" placeholder="Header名称" />
              </template>
            </el-table-column>
            <el-table-column prop="value" label="值">
              <template #default="scope">
                <el-input v-model="scope.row.value" placeholder="Header值" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click="removeHttpHeader(scope.$index)"
                  size="small"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" plain @click="addHttpHeader">添加HTTP头</el-button>
        </el-form-item>

        <el-form-item label="自定义User-Agent" prop="userAgent">
          <el-input
            v-model="policyForm.userAgent"
            placeholder="输入自定义User-Agent"
            maxlength="200"
            show-word-limit
          />
          <div class="form-hint">留空使用默认User-Agent</div>
        </el-form-item>

        <el-form-item label="启用漏洞验证" prop="enableVulnerabilityValidation">
          <el-switch v-model="policyForm.enableVulnerabilityValidation" />
          <div class="form-hint">对发现的漏洞进行自动验证</div>
        </el-form-item>

        <el-form-item label="启用代理" prop="enableProxy">
          <el-switch v-model="policyForm.enableProxy" />
        </el-form-item>

        <el-form-item v-if="policyForm.enableProxy" label="代理服务器" prop="proxyUrl">
          <el-input
            v-model="policyForm.proxyUrl"
            placeholder="例如: http://127.0.0.1:8080"
          />
        </el-form-item>

        <el-form-item label="启用状态" prop="status">
          <el-switch
            v-model="policyForm.status"
            active-value="enabled"
            inactive-value="disabled"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreatePolicyDialog = false">取消</el-button>
          <el-button type="primary" @click="savePolicy">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 运行策略扫描对话框 -->
    <el-dialog
      v-model="showRunScanDialog"
      :title="`运行扫描 - ${selectedPolicy?.name}`"
      width="600px"
    >
      <el-form
        ref="runScanFormRef"
        :model="runScanForm"
        :rules="runScanFormRules"
        label-width="120px"
      >
        <el-form-item label="扫描目标" prop="targets">
          <el-input
            v-model="runScanForm.targets"
            type="textarea"
            placeholder="请输入扫描目标，多个目标请用换行分隔\n例如：\nhttps://example.com\n192.168.1.0/24"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="扫描名称" prop="scanName">
          <el-input
            v-model="runScanForm.scanName"
            placeholder="请输入扫描任务名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="基准策略">
          <el-tag>{{ selectedPolicy?.name }}</el-tag>
        </el-form-item>
        <el-form-item label="通知配置">
          <el-checkbox-group v-model="runScanForm.notifications">
            <el-checkbox label="email" border class="mr-4">邮件</el-checkbox>
            <el-checkbox label="webhook" border class="mr-4">Webhook</el-checkbox>
            <el-checkbox label="system" border>系统通知</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="扫描优先级">
          <el-radio-group v-model="runScanForm.priority">
            <el-radio-button label="low">低</el-radio-button>
            <el-radio-button label="medium">中</el-radio-button>
            <el-radio-button label="high">高</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRunScanDialog = false">取消</el-button>
          <el-button type="primary" @click="executeScan" :loading="isExecutingScan">开始扫描</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Play, Upload, Download, Search, CopyDocument } from '@element-plus/icons-vue'
import apiService from '../services/apiService.js'
import { formatDate } from '../utils/dateUtils.js'

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const filterPolicyType = ref('')
const filterStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const selectedPolicies = ref([])
const showCreatePolicyDialog = ref(false)
const showRunScanDialog = ref(false)
const editingPolicy = ref(null)
const selectedPolicy = ref(null)
const isExecutingScan = ref(false)
const allPolicies = ref([])

// 策略表单
const policyForm = reactive({
  name: '',
  type: 'comprehensive',
  description: '',
  scanTypes: ['vulnerability'],
  scanSpeed: 2,
  concurrency: 5,
  timeout: 300,
  retryCount: 2,
  includedVulnerabilities: [],
  excludedVulnerabilities: [],
  severityThreshold: 'all',
  enableFingerprinting: true,
  enablePassiveScan: false,
  enableDeepScan: true,
  httpHeaders: [],
  userAgent: '',
  enableVulnerabilityValidation: true,
  enableProxy: false,
  proxyUrl: '',
  status: 'enabled'
})

// 运行扫描表单
const runScanForm = reactive({
  targets: '',
  scanName: '',
  notifications: ['system'],
  priority: 'medium'
})

// 表单验证规则
const policyFormRules = {
  name: [
    { required: true, message: '请输入策略名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择策略类型', trigger: 'change' }
  ],
  scanTypes: [
    { required: true, message: '请至少选择一种扫描类型', trigger: 'change' }
  ],
  proxyUrl: [
    {
      required: () => policyForm.enableProxy,
      message: '请输入代理服务器地址',
      trigger: 'blur'
    },
    {
      pattern: /^https?:\/\/.+/,
      message: '请输入有效的代理服务器地址',
      trigger: 'blur',
      required: false
    }
  ]
}

const runScanFormRules = {
  targets: [
    { required: true, message: '请输入扫描目标', trigger: 'blur' }
  ],
  scanName: [
    { required: true, message: '请输入扫描任务名称', trigger: 'blur' }
  ]
}

// 策略类型选项
const policyTypes = [
  { label: '全面扫描', value: 'comprehensive' },
  { label: '快速扫描', value: 'quick' },
  { label: '深度扫描', value: 'deep' },
  { label: '合规扫描', value: 'compliance' },
  { label: '自定义扫描', value: 'custom' }
]

// 可用扫描类型
const availableScanTypes = [
  { label: '漏洞扫描', value: 'vulnerability' },
  { label: '端口扫描', value: 'port' },
  { label: '服务识别', value: 'service' },
  { label: '配置检查', value: 'config' },
  { label: '弱口令扫描', value: 'brute_force' },
  { label: 'Web应用扫描', value: 'web' },
  { label: 'API扫描', value: 'api' },
  { label: '爬虫爬取', value: 'crawler' }
]

// 常见漏洞类型
const commonVulnerabilityTypes = [
  { label: 'SQL注入', value: 'sql_injection' },
  { label: '跨站脚本(XSS)', value: 'xss' },
  { label: '命令注入', value: 'command_injection' },
  { label: '文件包含', value: 'file_inclusion' },
  { label: 'CSRF', value: 'csrf' },
  { label: '认证绕过', value: 'auth_bypass' },
  { label: '信息泄露', value: 'info_disclosure' },
  { label: 'SSRF', value: 'ssrf' },
  { label: 'RCE', value: 'rce' },
  { label: '目录遍历', value: 'directory_traversal' },
  { label: '不安全配置', value: 'insecure_config' },
  { label: '弱密码', value: 'weak_password' },
  { label: '加密问题', value: 'encryption_issues' },
  { label: 'XPath注入', value: 'xpath_injection' },
  { label: 'LDAP注入', value: 'ldap_injection' },
  { label: 'XXE', value: 'xxe' },
  { label: '反序列化', value: 'deserialization' },
  { label: '缓冲区溢出', value: 'buffer_overflow' },
  { label: '拒绝服务', value: 'dos' }
]

// 计算属性
const filteredPolicies = computed(() => {
  let result = [...allPolicies.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(policy => 
      policy.name.toLowerCase().includes(query) ||
      policy.description.toLowerCase().includes(query)
    )
  }
  
  // 类型过滤
  if (filterPolicyType.value) {
    result = result.filter(policy => policy.type === filterPolicyType.value)
  }
  
  // 状态过滤
  if (filterStatus.value) {
    result = result.filter(policy => policy.status === filterStatus.value)
  }
  
  return result
})

const paginatedPolicies = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredPolicies.value.slice(start, end)
})

// 方法
const loadPolicies = async () => {
  loading.value = true
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.getScanPolicies()
    // allPolicies.value = response
    
    // 模拟数据
    allPolicies.value = [
      {
        id: '1',
        name: '全面安全扫描',
        type: 'comprehensive',
        scanTypes: ['vulnerability', 'port', 'service', 'config'],
        scanSpeed: 2,
        concurrency: 5,
        timeout: 300,
        retryCount: 2,
        includedVulnerabilities: [],
        excludedVulnerabilities: [],
        severityThreshold: 'all',
        enableFingerprinting: true,
        enablePassiveScan: false,
        enableDeepScan: true,
        httpHeaders: [],
        userAgent: '',
        enableVulnerabilityValidation: true,
        enableProxy: false,
        proxyUrl: '',
        description: '包含多种扫描类型的全面安全评估，适合常规安全检查',
        createdAt: '2024-01-10T08:30:00Z',
        status: 'enabled'
      },
      {
        id: '2',
        name: '快速漏洞检测',
        type: 'quick',
        scanTypes: ['vulnerability', 'port'],
        scanSpeed: 3,
        concurrency: 10,
        timeout: 180,
        retryCount: 1,
        includedVulnerabilities: [],
        excludedVulnerabilities: [],
        severityThreshold: 'medium',
        enableFingerprinting: true,
        enablePassiveScan: false,
        enableDeepScan: false,
        httpHeaders: [],
        userAgent: '',
        enableVulnerabilityValidation: false,
        enableProxy: false,
        proxyUrl: '',
        description: '快速扫描高危和中危漏洞，适合日常快速检测',
        createdAt: '2024-01-12T14:20:00Z',
        status: 'enabled'
      },
      {
        id: '3',
        name: '深度渗透测试',
        type: 'deep',
        scanTypes: ['vulnerability', 'brute_force', 'web', 'config'],
        scanSpeed: 1,
        concurrency: 3,
        timeout: 600,
        retryCount: 3,
        includedVulnerabilities: [],
        excludedVulnerabilities: [],
        severityThreshold: 'all',
        enableFingerprinting: true,
        enablePassiveScan: true,
        enableDeepScan: true,
        httpHeaders: [],
        userAgent: '',
        enableVulnerabilityValidation: true,
        enableProxy: false,
        proxyUrl: '',
        description: '深度渗透测试策略，包含弱口令检测和被动扫描',
        createdAt: '2024-01-15T09:45:00Z',
        status: 'enabled'
      },
      {
        id: '4',
        name: '合规性检查',
        type: 'compliance',
        scanTypes: ['config', 'vulnerability'],
        scanSpeed: 2,
        concurrency: 4,
        timeout: 480,
        retryCount: 2,
        includedVulnerabilities: [],
        excludedVulnerabilities: [],
        severityThreshold: 'all',
        enableFingerprinting: true,
        enablePassiveScan: false,
        enableDeepScan: false,
        httpHeaders: [],
        userAgent: '',
        enableVulnerabilityValidation: true,
        enableProxy: false,
        proxyUrl: '',
        description: '针对安全合规要求的配置和漏洞检查',
        createdAt: '2024-01-18T11:20:00Z',
        status: 'disabled'
      },
      {
        id: '5',
        name: 'Web应用专项',
        type: 'custom',
        scanTypes: ['web', 'crawler', 'vulnerability'],
        scanSpeed: 2,
        concurrency: 6,
        timeout: 420,
        retryCount: 2,
        includedVulnerabilities: ['sql_injection', 'xss', 'csrf', 'file_upload'],
        excludedVulnerabilities: [],
        severityThreshold: 'all',
        enableFingerprinting: true,
        enablePassiveScan: true,
        enableDeepScan: true,
        httpHeaders: [],
        userAgent: '',
        enableVulnerabilityValidation: true,
        enableProxy: false,
        proxyUrl: '',
        description: '针对Web应用的专项安全扫描，重点检查Web常见漏洞',
        createdAt: '2024-01-20T16:30:00Z',
        status: 'enabled'
      }
    ]
  } catch (error) {
    console.error('加载扫描策略失败:', error)
    ElMessage.error('加载扫描策略失败，请重试')
  } finally {
    loading.value = false
  }
}

const savePolicy = async () => {
  // 验证表单
  const policyFormRef = ref(null)
  if (!policyFormRef.value) {
    ElMessage.warning('表单验证失败')
    return
  }
  
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    if (editingPolicy.value) {
      // 更新现有策略
      const index = allPolicies.value.findIndex(p => p.id === editingPolicy.value.id)
      if (index !== -1) {
        allPolicies.value[index] = { ...policyForm, id: editingPolicy.value.id }
      }
      ElMessage.success('扫描策略更新成功')
    } else {
      // 创建新策略
      const newPolicy = {
        ...policyForm,
        id: String(allPolicies.value.length + 1),
        createdAt: new Date().toISOString()
      }
      allPolicies.value.unshift(newPolicy)
      ElMessage.success('扫描策略创建成功')
    }
    
    showCreatePolicyDialog.value = false
    resetPolicyForm()
  } catch (error) {
    console.error('保存扫描策略失败:', error)
    ElMessage.error('保存扫描策略失败，请重试')
  }
}

const deletePolicy = async (policy) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除扫描策略"${policy.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里模拟API调用，实际项目中应该调用真实API
    allPolicies.value = allPolicies.value.filter(p => p.id !== policy.id)
    ElMessage.success('扫描策略删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

const cloneSelectedPolicy = () => {
  if (selectedPolicies.value.length !== 1) {
    ElMessage.warning('请选择一个策略进行克隆')
    return
  }
  
  const originalPolicy = selectedPolicies.value[0]
  // 复制策略但生成新ID和名称
  const clonedPolicy = {
    ...JSON.parse(JSON.stringify(originalPolicy)),
    id: String(allPolicies.value.length + 1),
    name: `${originalPolicy.name} - 克隆`,
    createdAt: new Date().toISOString()
  }
  
  allPolicies.value.unshift(clonedPolicy)
  ElMessage.success('策略克隆成功')
}

const updatePolicyStatus = async (policy) => {
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    ElMessage.success(`扫描策略已${policy.status === 'enabled' ? '启用' : '禁用'}`)
  } catch (error) {
    // 回滚状态更改
    policy.status = policy.status === 'enabled' ? 'disabled' : 'enabled'
    console.error('更新策略状态失败:', error)
    ElMessage.error('更新策略状态失败，请重试')
  }
}

const editPolicy = (policy) => {
  editingPolicy.value = policy
  // 深拷贝以避免直接修改原对象
  const policyCopy = JSON.parse(JSON.stringify(policy))
  Object.assign(policyForm, policyCopy)
  showCreatePolicyDialog.value = true
}

const runPolicyScan = (policy) => {
  selectedPolicy.value = policy
  runScanForm.scanName = `${policy.name} - ${formatDate(new Date())}`
  runScanForm.targets = ''
  runScanForm.notifications = ['system']
  runScanForm.priority = 'medium'
  showRunScanDialog.value = true
}

const executeScan = async () => {
  // 验证表单
  const runScanFormRef = ref(null)
  if (!runScanFormRef.value) {
    ElMessage.warning('表单验证失败')
    return
  }
  
  isExecutingScan.value = true
  
  try {
    // 这里模拟API调用，实际项目中应该调用真实API
    // const response = await apiService.createScanTask({
    //   ...runScanForm,
    //   policyId: selectedPolicy.value.id
    // })
    
    // 模拟成功响应
    setTimeout(() => {
      ElMessage.success(`扫描任务 "${runScanForm.scanName}" 已创建成功`)
      showRunScanDialog.value = false
      isExecutingScan.value = false
    }, 1500)
  } catch (error) {
    console.error('创建扫描任务失败:', error)
    ElMessage.error('创建扫描任务失败，请重试')
    isExecutingScan.value = false
  }
}

const importPolicy = () => {
  // 这里应该实现导入功能，打开文件选择器
  ElMessage.info('导入策略功能待实现')
}

const exportSelectedPolicies = () => {
  if (selectedPolicies.value.length === 0) {
    ElMessage.warning('请选择要导出的扫描策略')
    return
  }
  
  // 这里应该实现导出功能
  ElMessage.success(`已导出${selectedPolicies.value.length}个扫描策略`)
}

const handleSelectionChange = (selection) => {
  selectedPolicies.value = selection
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleFilter = () => {
  currentPage.value = 1
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
}

const handleCurrentChange = (newCurrent) => {
  currentPage.value = newCurrent
}

const resetPolicyForm = () => {
  Object.assign(policyForm, {
    name: '',
    type: 'comprehensive',
    description: '',
    scanTypes: ['vulnerability'],
    scanSpeed: 2,
    concurrency: 5,
    timeout: 300,
    retryCount: 2,
    includedVulnerabilities: [],
    excludedVulnerabilities: [],
    severityThreshold: 'all',
    enableFingerprinting: true,
    enablePassiveScan: false,
    enableDeepScan: true,
    httpHeaders: [],
    userAgent: '',
    enableVulnerabilityValidation: true,
    enableProxy: false,
    proxyUrl: '',
    status: 'enabled'
  })
  editingPolicy.value = null
}

const addHttpHeader = () => {
  policyForm.httpHeaders.push({ name: '', value: '' })
}

const removeHttpHeader = (index) => {
  policyForm.httpHeaders.splice(index, 1)
}

const isSelectedScanType = (type) => {
  return policyForm.scanTypes.includes(type)
}

// 辅助函数
const getPolicyTypeTag = (type) => {
  const typeMap = {
    'comprehensive': 'primary',
    'quick': 'success',
    'deep': 'warning',
    'compliance': 'danger',
    'custom': 'info'
  }
  return typeMap[type] || 'default'
}

const getPolicyTypeLabel = (type) => {
  const labelMap = policyTypes.reduce((map, t) => {
    map[t.value] = t.label
    return map
  }, {})
  return labelMap[type] || type
}

const getScanTypeLabel = (type) => {
  const labelMap = availableScanTypes.reduce((map, t) => {
    map[t.value] = t.label
    return map
  }, {})
  return labelMap[type] || type
}

// 组件挂载时加载数据
onMounted(() => {
  loadPolicies()
})
</script>

<style scoped>
.scan-policies-container {
  padding: 20px;
}

.policies-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-filter-container {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.policies-table-container {
  overflow-x: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.policy-name-cell {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.policy-name {
  font-weight: 500;
}

.policy-description {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.scan-types {
  display: flex;
  flex-wrap: wrap;
}

.mr-2 {
  margin-right: 8px;
}

.mr-4 {
  margin-right: 16px;
}

.mb-2 {
  margin-bottom: 8px;
}

.form-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .scan-policies-container {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .search-filter-container {
    padding: 12px;
  }
  
  .el-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .el-col {
    width: 100% !important;
  }
}
</style>